package com.shi.yibanjia.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shi.yibanjia.common.Result;
import com.shi.yibanjia.common.UserContext;
import com.shi.yibanjia.entity.po.Comments;
import com.shi.yibanjia.service.CommentsService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/app/comment")
public class CommentController {

    @Resource
    private CommentsService commentsService;

    @PostMapping
    @CacheEvict(value = "yibanjia:comment", allEntries = true)
    public Result addComment(@RequestBody Comments comments) {
        comments.setUid(UserContext.getUser().getId());
        commentsService.save(comments);
        return Result.ok();
    }

    @GetMapping("/{page}/{size}")
    @Cacheable(value = "yibanjia:comment", key = "'page:'+#page+':size:'+#size+':level:'+#level")
    public Result list(@PathVariable("page") Integer page,
                       @PathVariable("size") Integer size,
                       @RequestParam("level") String level) {
        List<Integer> starsList;
        if ("a".equals(level)) {
            starsList = List.of(5, 4);
        } else if ("b".equals(level)) {
            starsList = List.of(3);
        } else {
            starsList = List.of(1, 2);
        }
        return Result.ok(commentsService.getCommentWithNicknameByPage(new Page<>(page, size), starsList));
    }

    @GetMapping("/user/{userId}/{page}/{size}")
    @Cacheable(value = "yibanjia:comment", key = "'userId:'+#userId+':page:'+#page+':size:'+#size")
    public Result listByUserId(@PathVariable("userId") Long userId,
                               @PathVariable("page") Integer page,
                               @PathVariable("size") Integer size) {
        return Result.ok(commentsService.getCommentWithNicknameByUserId(new Page<>(page, size), userId));
    }

    @DeleteMapping("/{commentId}")
    @CacheEvict(value = "yibanjia:comment", allEntries = true)
    public Result removeComment(@PathVariable("commentId") Long commentId) {
        commentsService.removeById(commentId);
        return Result.ok();
    }
}
